//
//  NetManager.m
//  03-28-20606ApiDemo
//
//  Created by student on 16/3/29.
//  Copyright © 2016年 niit. All rights reserved.
//

#import "NetManager.h"

@implementation NetManager
+(NSString *)requestInfoByPersonId:(NSString *)personId
{
    NSString *httpUrl = @"http://apis.baidu.com/apistore/idservice/id";
    NSString *httpArg = [NSString stringWithFormat:@"id=%@",personId];
    //网址字符串
    NSString *urlStr = [[NSString alloc]initWithFormat:@"%@?%@",httpUrl,httpArg];
    //网址
    NSURL *url  = [NSURL URLWithString:urlStr];
    
    //请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    //GET请求
    [request setHTTPMethod:@"GET"];
    
    //设置请求头
    
    [request addValue: @"a47710812a161be75ac6713a123dcbde" forHTTPHeaderField: @"apikey"];
    
    NSError *error;
    NSData *data =[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
    if (error!=nil) {
        return  nil;
    }
    NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    NSDictionary *dict1=dict[@"retData"];
    
    NSString *result= [NSString stringWithFormat:@"生日:%@\n地址:%@\n性别:%@",dict1[@"birthday"],dict1[@"address"],dict1[@"sex"]];
    
    return result;
}

+(void)requestInfoByPersonId:(NSString *)personId
                successBlock:(void(^)(NSString *))successBlock
                   failBlock:(void(^)(NSError *))failBlock
{
    NSString *httpUrl = @"http://apis.baidu.com/apistore/idservice/id";
    NSString *httpArg = [NSString stringWithFormat:@"id=%@",personId];
    //网址字符串
    NSString *urlStr = [[NSString alloc]initWithFormat:@"%@?%@",httpUrl,httpArg];
    //网址
    NSURL *url  = [NSURL URLWithString:urlStr];
    
    //请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    //GET请求
    [request setHTTPMethod:@"GET"];
    
    //设置请求头
    
    [request addValue: @"a47710812a161be75ac6713a123dcbde" forHTTPHeaderField: @"apikey"];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError==nil) {
            NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSDictionary *dict1=dict[@"retData"];
            NSString *result= [NSString stringWithFormat:@"生日:%@\n地址:%@\n性别:%@",dict1[@"birthday"],dict1[@"address"],dict1[@"sex"]];
            
            successBlock(result);
        }
        else{
            failBlock(connectionError);
        }
    }];
}
@end
